package lcd

// MenuConfig 菜单配置
type MenuConfig struct {
	Items []*MenuItem
}

// NewMenuConfig 创建新的菜单配置
func NewMenuConfig() *MenuConfig {
	return &MenuConfig{
		Items: make([]*MenuItem, 0),
	}
}

// AddRootItem 添加根菜单项
func (c *MenuConfig) AddRootItem(item *MenuItem) {
	c.Items = append(c.Items, item)
}

// GetRootItems 获取所有根菜单项
func (c *MenuConfig) GetRootItems() []*MenuItem {
	return c.Items
}

// FindItemByID 通过ID查找菜单项
func (c *MenuConfig) FindItemByID(id string) *MenuItem {
	return findItemByID(c.Items, id)
}

// findItemByID 递归查找菜单项
func findItemByID(items []*MenuItem, id string) *MenuItem {
	for _, item := range items {
		if item.ID == id {
			return item
		}
		if len(item.Children) > 0 {
			if found := findItemByID(item.Children, id); found != nil {
				return found
			}
		}
	}
	return nil
}

// DefaultMenuConfig 创建默认菜单配置
func DefaultMenuConfig() *MenuConfig {
	config := NewMenuConfig()

	// 温度设置菜单
	tempMenu := &MenuItem{
		ID:      "temp",
		Type:    MenuItemTypeNormal,
		Display: "TEMP",
	}
	config.AddRootItem(tempMenu)

	// 温度阈值设置
	highTemp := &MenuItem{
		ID:       "high_temp",
		Type:     MenuItemTypeValue,
		Display:  "HI",
		MinValue: intPtr(200),
		MaxValue: intPtr(300),
		Step:     intPtr(5),
	}
	tempMenu.AddChild(highTemp)

	lowTemp := &MenuItem{
		ID:       "low_temp",
		Type:     MenuItemTypeValue,
		Display:  "LO",
		MinValue: intPtr(180),
		MaxValue: intPtr(250),
		Step:     intPtr(5),
	}
	tempMenu.AddChild(lowTemp)

	// 功率设置菜单
	powerMenu := &MenuItem{
		ID:      "power",
		Type:    MenuItemTypeNormal,
		Display: "POW",
	}
	config.AddRootItem(powerMenu)

	maxPower := &MenuItem{
		ID:       "max_power",
		Type:     MenuItemTypeValue,
		Display:  "MAX",
		MinValue: intPtr(50),
		MaxValue: intPtr(100),
		Step:     intPtr(5),
	}
	powerMenu.AddChild(maxPower)

	minPower := &MenuItem{
		ID:       "min_power",
		Type:     MenuItemTypeValue,
		Display:  "MIN",
		MinValue: intPtr(0),
		MaxValue: intPtr(40),
		Step:     intPtr(5),
	}
	powerMenu.AddChild(minPower)

	// 模式设置菜单
	modeMenu := &MenuItem{
		ID:      "mode",
		Type:    MenuItemTypeNormal,
		Display: "MODE",
	}
	config.AddRootItem(modeMenu)

	autoMode := &MenuItem{
		ID:      "auto",
		Type:    MenuItemTypeNormal,
		Display: "AUTO",
	}
	modeMenu.AddChild(autoMode)

	heatMode := &MenuItem{
		ID:      "heat",
		Type:    MenuItemTypeNormal,
		Display: "HEAT",
	}
	modeMenu.AddChild(heatMode)

	pumpMode := &MenuItem{
		ID:      "pump",
		Type:    MenuItemTypeNormal,
		Display: "PUMP",
	}
	modeMenu.AddChild(pumpMode)

	return config
}

// intPtr 创建int指针
func intPtr(v int) *int {
	return &v
}
